const ffmpeg = require('fluent-ffmpeg')
const path = require('path')
const fs = require('fs')

// 生成缩略图中间件
exports.generateThumbnail = async (req, res, next) => {
  // 检查是否有 video 文件
  if (!req.files || !req.files.video || req.files.video.length === 0) return next();
  // 如果用户上传了 thumbnail，则跳过自动生成
  if (req.files.thumbnail && req.files.thumbnail.length > 0) return next();

  const videoFile = req.files.video[0];

  try {
    const thumbnailDir = path.join(__dirname, '../../uploads/thumbnails')
    if (!fs.existsSync(thumbnailDir)) {
      fs.mkdirSync(thumbnailDir, { recursive: true })
    }

    const thumbnailFilename = `${Date.now()}-${Math.round(Math.random() * 1E9)}.jpg`
    const thumbnailPath = path.join(thumbnailDir, thumbnailFilename)

    await new Promise((resolve, reject) => {
      ffmpeg(videoFile.path) // 使用 videoFile.path
        .screenshots({
          timestamps: ['00:00:01'],
          filename: thumbnailFilename,
          folder: thumbnailDir,
          size: '1280x720'
        })
        .on('end', () => {
          // 将生成的缩略图路径附加到 video 文件对象上
          videoFile.thumbnail = `/uploads/thumbnails/${thumbnailFilename}`
          resolve()
        })
        .on('error', reject)
    })

    next()
  } catch (error) {
    console.error('生成缩略图失败:', error)
    next(error)
  }
}

// 获取视频信息中间件
exports.getVideoInfo = async (req, res, next) => {
  // 检查是否有 video 文件
  if (!req.files || !req.files.video || req.files.video.length === 0) return next();

  const videoFile = req.files.video[0];

  try {
    const metadata = await new Promise((resolve, reject) => {
      ffmpeg.ffprobe(videoFile.path, (err, metadata) => { // 使用 videoFile.path
        if (err) return reject(err)
        resolve(metadata)
      })
    })

    // 将视频信息附加到 req 对象上
    req.videoInfo = {
      duration: metadata.format.duration,
      width: metadata.streams[0].width,
      height: metadata.streams[0].height,
      bitrate: metadata.format.bit_rate
    }

    next()
  } catch (error) {
    console.error('获取视频信息失败:', error)
    next(error)
  }
}

// 清理上传文件中间件
exports.cleanupUpload = (req, res, next) => {
  // 将清理函数附加到 req 对象，以便在控制器中使用
  req.cleanupUpload = () => {
    try {
      // 检查是否有 files 对象
      if (!req.files) return;

      const videoFile = req.files.video ? req.files.video[0] : null;
      const thumbnailFile = req.files.thumbnail ? req.files.thumbnail[0] : null;

      // 删除视频文件
      if (videoFile && fs.existsSync(videoFile.path)) {
        fs.unlinkSync(videoFile.path);
      }

      // 删除上传的缩略图文件
      if (thumbnailFile && fs.existsSync(thumbnailFile.path)) {
        fs.unlinkSync(thumbnailFile.path);
      }

      // 删除自动生成的缩略图
      if (videoFile && videoFile.thumbnail) {
        const generatedThumbnailPath = path.join(__dirname, '../..', videoFile.thumbnail);
        if (fs.existsSync(generatedThumbnailPath) && (!thumbnailFile || generatedThumbnailPath !== thumbnailFile.path)) {
          fs.unlinkSync(generatedThumbnailPath);
        }
      }
    } catch (error) {
      console.error('清理上传文件失败:', error);
    }
  };

  // 在请求结束时自动清理文件（如果发生错误）
  res.on('finish', () => {
    if (res.statusCode >= 400 && req.cleanupUpload) {
      req.cleanupUpload();
    }
  });

  next();
};